package cn.rengy.web.framework.wxmp.qrcode;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.bean.BeanUtil;
import cn.rengy.tpa.wxmp.token.AccessToken;
import cn.rengy.tpa.wxmp.user.AccountManager;
import cn.rengy.tpa.wxmp.user.Qrcode;
import cn.rengy.web.framework.id.IdGenerator;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.wxmp.token.AccessTokenCacheService;

@Service
public class WxQrcodeService {
	@Autowired
	private DbService dbService;
	@Autowired
	private AccessTokenCacheService accessTokenCacheService;
	@Autowired
	private IdGenerator idGenerator;
	/**
	 * 回收二维码
	 */
	public void recycle(String scene_str) {
		this.dbService.update("update_wxqrcode_qr_status", 4,scene_str);
	}
	/**
	 * 拉取一个二维码
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)//非事务模式
	public WxQrcodeEntity add(String appid) {
		String scene_str=idGenerator.generateId().toString();
		AccessToken accessToken=accessTokenCacheService.getAccessToken(appid);
		Qrcode qrcode=AccountManager.createQrcodePerpetual(accessToken, scene_str);
		WxQrcodeEntity wxQrcodeEntity=new WxQrcodeEntity();
		BeanUtil.copyProperties(qrcode, wxQrcodeEntity);
		wxQrcodeEntity.setAppid(appid);
		wxQrcodeEntity.setCreate_time(new Date());
		wxQrcodeEntity.setQr_status(1);//1空闲2提取中3已占用4已回收
		this.dbService.updateBeanParameter("insert_wx_qrcode", wxQrcodeEntity);
		return wxQrcodeEntity;
	}
	
	/**
	 * 拉取一批二维码
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)//非事务模式
	public void pull(String appid,int count) {
		if(count>100) {
			count=100;
		}
		for(int i=0;i<100;i++) {
			add(appid);
		}
	}
}
